<script lang="ts" setup>
import { useUserStore } from '@/stores/user'
import { baseURL } from '@/utils/request'

import RoomStatus from './components/room-status.vue'
import PatientInfo from './components/patient-info.vue'
import NotifyInfo from './components/notify-info.vue'
import MessageInfo from './components/message-info.vue'
import PrescriptionInfo from './components/prescription-info.vue'
import RateInfo from './components/rate-info.vue'
import { orderDetailApi, uploadImageAPI } from '@/apis/consult'
import { ref } from 'vue'
import type { OrderDetail } from '@/types/consult'
import io from '@hyoga/uni-socket.io'
import type { ChatMsgListData, MsgItem } from '@/types/room'
import { nextTick } from 'vue'
const props = defineProps<{
  orderId: string
  type: string
  payResult: 'true' | 'false'
}>()
const store = useUserStore()
const socket = io(baseURL, {
  auth: { token: `Bearer ${store.token}` },
  query: {
    orderId: props.orderId,
  },
  transports: ['websocket', 'polling'],
  timeout: 15 * 1000,
})
const orderDetail = ref<OrderDetail>()
const getOrderDetail = async () => {
  const res = await orderDetailApi(props.orderId)
  console.log(res)
  orderDetail.value = res.data
}
getOrderDetail()
const messageList = ref<MsgItem[]>([])

// 监听订单状态变化，statusChange 为后端定义的事件名称
socket.on('statusChange', () => {
  // 重新获取订单详情，包含订单状态，倒计时秒数
  getOrderDetail()
})

socket.on('chatMsgList', (res: ChatMsgListData) => {
  if (res.code !== 10000) return
  res.data?.forEach((item) => {
    if (item.items) {
      messageList.value.push(
        {
          msgType: 31,
          createTime: item.createTime,
          msg: {
            content: item.createTime,
          },
        },
        ...item.items
      )
    }
  })
  console.log(messageList.value)
})
socket.on('connect', () => {
  console.log('连接成功')
})

socket.on('disconnect', () => {
  console.log('连接失败')
})
const scrollIntoViewId = ref('')
socket.on('receiveChatMsg', async (message: MsgItem) => {
  socket.emit('updateMsgStatus', message.id)
  messageList.value.push(message)
  await nextTick()
  scrollIntoViewId.value = `id-${message.id}`
})
const message = ref('')
const sendMessage = () => {
  if (message.value.trim() === '') {
    uni.showToast({
      title: '请输入内容',
      icon: 'none',
    })
    return
  }
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id,
    to: orderDetail.value?.docInfo.id,
    msgtype: 1,
    msg: {
      content: message.value, // 文本消息内容
    },
  })
  message.value = ''
}
const handleUploadImage = async () => {
  if (orderDetail.value?.status !== 3) {
    uni.showToast({
      title: '咨询未开始，不能发送图片',
      icon: 'none',
    })
    return
  }
  const { tempFilePaths } = await uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
  })
  const res = await uploadImageAPI(tempFilePaths[0])
  console.log(res)
  // 7.4 发送图片消息
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id,
    to: orderDetail.value?.docInfo?.id,
    msgType: 4,
    msg: {
      picture: {
        url: res.data.url,
        id: res.data.id,
      },
    },
  })
}
</script>

<template>
  <view class="room-page">
    <!-- 咨询室组件 -->
    <RoomStatus
      v-if="orderDetail?.id"
      :status="orderDetail?.status"
      :status-value="orderDetail?.statusValue"
      :countdown="orderDetail?.countdown"
    />
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="scrollIntoViewId"
    >
      <view class="message-container">
        <view v-for="item in messageList" :key="item.id" :id="`id-${item.id}`">
          <PatientInfo v-if="item.msgType === 21" :info="item.msg?.consultRecord" />
          <NotifyInfo v-else-if="item.msgType && item.msgType >= 31" :type="item.msgType">
            {{ item.msg?.content }}
          </NotifyInfo>
          <MessageInfo v-else-if="item.msgType === 1 || item.msgType === 4" :message="item" />
          <PrescriptionInfo v-else-if="item.msgType === 22" :info="item.msg?.prescription" />
          <RateInfo v-else-if="item.msgType === 23" />
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          @confirm="sendMessage"
          v-model="message"
          :disabled="orderDetail?.status !== 3"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button" @click="handleUploadImage">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
